﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_DLL.Product.database;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_PRODUCT.Product.DAO;
using ERP_RORZE_DLL.Product.Base;
using System.Data.OleDb;
using System.Data.SqlClient;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.BizLogic;

namespace ERP_RORZE_PRODUCT.Product.Incauhinhmoi
{
    public partial class ctrlConfigureData : DevExpress.XtraEditors.XtraUserControl
    {
        ConfigureData b = new ConfigureData();
        ClsIncauhinhDAO clsConfigureDAO = new ClsIncauhinhDAO();
        private LogUtils log;

        DataTable dt;

        public ctrlConfigureData()
        {
            InitializeComponent();
            log = new LogUtils();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frm_ConfigureDataEdit frmEdit = new frm_ConfigureDataEdit();
            frmEdit.ID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString();
            frmEdit.Activate();
            frmEdit.Show();
            Cursor.Current = Cursors.Default;
        }
        void Reload(object sender, EventArgs e)
        {
            dt = clsConfigureDAO.GetAllConfigureData();
            gridControl1.DataSource = dt;
            gridView1.BestFitColumns();
        }
        private void btDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có thực sự muốn xóa dữ liệu!", "Message", MessageBoxButtons.OKCancel,
                                MessageBoxIcon.Question) == DialogResult.OK)
            {
                b.ID = int.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString());
                b.PartNo = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "PartNo").ToString();
                clsConfigureDAO.DeleteConfigureData(b);

                //write Log
                log.Table = LogConstant.Table.Product.ConfigureData;
                log.Task = LogConstant.Task.Delete;
                log.Description = "PartNo: " + b.PartNo;
                log.WriteLog();

                Reload(sender, e);
            }
        }

        private void ctrlConfigureData_Load(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frm_ConfigureDataAdd frmAdd = new frm_ConfigureDataAdd();
            frmAdd.Reload += new EventHandler(Reload);
            frmAdd.Activate();
            frmAdd.Show();
            Cursor.Current = Cursors.Default;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            btnAddNew_Click(sender, e);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            btDelete_Click(sender, e);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            btEdit_Click(sender, e);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            clsConstantsFuction.ExportToExcel(gridView1, 1, true);
        }

        private void ImportData()
        {
            INISettings mySetting = new INISettings();
            SqlConnection myConnection = new SqlConnection(mySetting.SQLConnectionString);

            FileDialog importFile = new OpenFileDialog();
            importFile.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            if (importFile.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection excelConnection = null;
                try
                {
                    Control parent = progressPanel1.Parent;
                    progressPanel1.Location =
                        new Point(parent.Bounds.X + parent.Bounds.Width / 2 - progressPanel1.Width / 2,
                                  parent.Bounds.Y + parent.Bounds.Height / 2 - progressPanel1.Height / 2);
                    progressPanel1.Visible = true;
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                                                   importFile.FileName +
                                                   ";Extended Properties=Excel 12.0;Persist Security Info=False";
                    excelConnection = new OleDbConnection(excelConnectionString);
                    OleDbCommand cmd =
                        new OleDbCommand("Select [date],[Shift],[MachineID],[StaffID] ,[MONo] " +
                                         ",[OptionID] ,[WorkID] ,[time] ,[OKQty],[NGQty],[ProTime]" +
                                         ",[Clamptime],[Note1],[Note2],[From],[To],[SProTime],[SClampTime],[TOKQty],[TNGQty] from [Sheet1$]",
                                         excelConnection);
                    excelConnection.Open();
                    OleDbDataReader dReader;
                    dReader = cmd.ExecuteReader();
                    int i = 0;
                    //int countDup = 0;
                    //int line = 1;
                    //string lineDup = string.Empty;

                    myConnection.Open();
                    while (dReader.Read())
                    {
                        //bool exist = false;
                        //line++;
                        //try
                        //{
                        //    SqlCommand cmd_sql = myConnection.CreateCommand();
                        //    cmd_sql.CommandText = "SELECT * FROM [242_LaborWTS] " +
                        //                          "WHERE [date]='" + dReader["date"].ToString() + "' " +
                        //                          " and [Shift]='" + dReader["Shift"].ToString() + "'" +
                        //                          " and [MachineID]=N'" + dReader["MachineID"].ToString() + "'" +
                        //                          " and [StaffID]='" + dReader["StaffID"].ToString() + "'" +
                        //                          " and [MONo]='" + dReader["MONo"].ToString() + "'" +
                        //                          " and [OptionID]='" + dReader["OptionID"].ToString() + "'" +
                        //                          " and [WorkID]='" + dReader["WorkID"].ToString() + "'" +
                        //                          " and [time]=" + dReader["time"].ToString() +
                        //                          " and [OKQty]=" + dReader["OKQty"].ToString() + 
                        //                          " and [NGQty]=" + dReader["NGQty"].ToString() + 
                        //                          " and [ProTime]=" + dReader["ProTime"].ToString() + 
                        //                          " and [Clamptime]=" + dReader["Clamptime"].ToString() +
                        //                          " and [Note1]=N'" + dReader["Note1"].ToString() + "'" +
                        //                          " and [Note2]=N'" + dReader["Note2"].ToString() + "'" +
                        //                          " and [From]='" + dReader["From"].ToString() + "'" +
                        //                          " and [To]='" + dReader["To"].ToString() + "'" +
                        //                          " and [SProTime]=" + dReader["SProTime"].ToString() + 
                        //                          " and [SClampTime]=" + dReader["SClampTime"].ToString() +
                        //                          " and [TOKQty]=" + dReader["TOKQty"].ToString() + 
                        //                          " and [TNGQty]=" + dReader["TNGQty"].ToString();
                        //    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                        //    if (dataReader.Read())
                        //    {

                        //        exist = true;
                        //        countDup++;

                        //        lineDup += line.ToString() + ", ";
                        //    }
                        //    dataReader.Close();
                        //    cmd_sql.Dispose();
                        //}
                        //catch
                        //{
                        //    exist = true;
                        //}

                        //if (!exist)
                        //{

                        string date = (dReader["date"].ToString().Equals(string.Empty)) ? "null" : "'" + dReader["date"].ToString() + "'";
                        string shift = (dReader["Shift"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["Shift"].ToString() + "'";
                        string staffID = (dReader["StaffID"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["StaffID"].ToString() + "'";
                        string machineID = (dReader["MachineID"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["MachineID"].ToString() + "'";
                        string mONo = (dReader["MONo"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["MONo"].ToString() + "'";
                        string optionID = (dReader["OptionID"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["OptionID"].ToString() + "'";
                        string workID = (dReader["WorkID"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["WorkID"].ToString() + "'";
                        string time = (dReader["time"].ToString().Equals(string.Empty)) ? "null" : dReader["time"].ToString();
                        string oKQty = (dReader["OKQty"].ToString().Equals(string.Empty)) ? "null" : dReader["OKQty"].ToString();
                        string nGQty = (dReader["NGQty"].ToString().Equals(string.Empty)) ? "null" : dReader["NGQty"].ToString();
                        string proTime = (dReader["ProTime"].ToString().Equals(string.Empty)) ? "null" : dReader["ProTime"].ToString();
                        string clamptime = (dReader["Clamptime"].ToString().Equals(string.Empty)) ? "null" : dReader["Clamptime"].ToString();
                        string note1 = (dReader["Note1"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["Note1"].ToString() + "'";
                        string note2 = (dReader["Note2"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["Note2"].ToString() + "'";
                        string from = (dReader["From"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["From"].ToString() + "'";
                        string to = (dReader["To"].ToString().Equals(string.Empty)) ? "null" : "N'" + dReader["To"].ToString() + "'";
                        string sProTime = (dReader["SProTime"].ToString().Equals(string.Empty)) ? "null" : dReader["SProTime"].ToString();
                        string sClampTime = (dReader["SClampTime"].ToString().Equals(string.Empty)) ? "null" : dReader["SClampTime"].ToString();
                        string tOKQty = (dReader["TOKQty"].ToString().Equals(string.Empty)) ? "null" : dReader["TOKQty"].ToString();
                        string tNGQty = (dReader["TNGQty"].ToString().Equals(string.Empty)) ? "null" : dReader["TNGQty"].ToString();


                        string sql = "INSERT INTO [242_LaborWTS] ("
                                     + "[date],[Shift],[StaffID],[MachineID] ,[MONo] "
                                     + ",[OptionID] ,[WorkID] ,[time] ,[OKQty],[NGQty],[ProTime]"
                                     + ",[Clamptime],[Note1],[Note2],[From],[To],[SProTime],[SClampTime],[TOKQty],[TNGQty] )"
                                     + " VALUES (" + date + ", " + shift + ", " + staffID + ","
                                     + machineID + "," + mONo + ", " + optionID + ", " + workID + ", " + time + ", "
                                     + oKQty + " ," + nGQty + ", " + proTime + ", " + clamptime + ", " + note1 + ", " + note2 + ", "
                                     + from + ", " + to + ", " + sProTime + ", " + sClampTime + ", " + tOKQty + ", " + tNGQty + ")";
                        SqlCommand cmd_sql = new SqlCommand(sql, myConnection);

                        cmd_sql.ExecuteNonQuery();
                        cmd_sql.Dispose();
                        i++;
                        //}
                    }
                    myConnection.Close();
                    //progressPanel1.Visible = false;
                    excelConnection.Close();
                    MessageBox.Show(i + " records have been imported.");
                    //MessageBox.Show(i + " records have been imported. \n" + countDup.ToString() + " record(s) duplicated (Lines: " + lineDup.Substring(0, lineDup.Length - 1) + ")");
                    //LoadData();
                }
                catch (Exception ex)
                {
                    if (excelConnection.State == ConnectionState.Open)
                    {
                        excelConnection.Close();
                    }
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                }

            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (gridView1.SelectedRowsCount > 0)
            {
                var row = new DataRow[gridView1.SelectedRowsCount];
                var frequencyId = new string[gridView1.SelectedRowsCount];

                for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                {
                    row[i] = gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
                    frequencyId[i] = row[i]["ID"].ToString();
                }


                if (MessageBox.Show("Chắc chắn muốn chọn in các cấu hình này", ToolConstants.Form.MessageBox.Message,
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    for (int i = 0; i < frequencyId.Length; i++)
                    {
                        b.ID = int.Parse(frequencyId[i]);
                        clsConfigureDAO.ChonIn(b);

                        //write Log
                        log.Table = LogConstant.Table.Product.ConfigureData;
                        log.Task = LogConstant.Task.Update;
                        log.Description = "Chọn in ID: " + b.ID;
                        log.WriteLog();

                        Reload(sender, e);
                    }

                }
            }
            else
            {
                MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        private void btnTichchon_Click(object sender, EventArgs e)
        {
            btnPrint_Click(sender, e);
        }

        private void btnBochon_Click(object sender, EventArgs e)
        {
            if (gridView1.SelectedRowsCount > 0)
            {
                var row = new DataRow[gridView1.SelectedRowsCount];
                var frequencyId = new string[gridView1.SelectedRowsCount];

                for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                {
                    row[i] = gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
                    frequencyId[i] = row[i]["ID"].ToString();
                }


                if (MessageBox.Show("Thực sự muốn bỏ chọn in các cấu hình này", ToolConstants.Form.MessageBox.Message,
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    for (int i = 0; i < frequencyId.Length; i++)
                    {
                        b.ID = int.Parse(frequencyId[i]);
                        clsConfigureDAO.BoChonIn(b);

                        //write Log
                        log.Table = LogConstant.Table.Product.ConfigureData;
                        log.Task = LogConstant.Task.Update;
                        log.Description = "Bỏ chọn in ID: " + b.ID;
                        log.WriteLog();

                        Reload(sender, e);
                    }

                }
            }
            else
            {
                MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
    }
}
